package com.college.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.college.domain.Department;
import com.college.domain.Faculty;
import com.college.domain.Roles;
import com.college.domain.Users;
import com.college.interfaces.IFacultyDAO;
import com.college.interfaces.IRolesDAO;
import com.college.interfaces.IUserDAO;

@Repository
@Transactional
public class FacultyDAO implements IFacultyDAO {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	private IUserDAO userDAO;
	
	@Autowired
	private IRolesDAO rolesDAO;
	
	@Override
	@Transactional
	public int saveFacultyInfo(Users user, Faculty faculty, Roles role,
			Department dept) {
		userDAO.saveUser(user);
		List<Users> userObj =  userDAO.getUserByUsername(user.getUserName());
		for(Users user1: userObj){
		role.setUserId(user.getUserId());
		}
		rolesDAO.saveRole(role);
		List<Department> dept1 = getDeptByCollegeDeptName(dept);
		for(Department dep: dept1){
		faculty.setDeptId(dep.getDeptId());
		}
		faculty.setRoleId(role.getRoleId());
		savefaculty(faculty);
		
		
		return 0;
	}

	@Override
	public void savefaculty(Faculty faculty) {
		sessionFactory.getCurrentSession().save(faculty);
		
	}

	@Override
	public List<Department> getDeptByCollegeDeptName(Department dept) {
		return sessionFactory.getCurrentSession().createQuery("from Department where deptName=:deptName and collegeName=:collegeName")
		.setString("deptName", dept.getDeptName()).setString("collegeName", dept.getCollegeName()).list();
	}

	@Override
	public List<Faculty> getAllFAcultyByNameOrId(String searchKey) {

		String whereClause =null;
		String colName = null;
		
		if(iskeyNumeric(searchKey)){
		whereClause = "from Faculty where facultyId=:searchKey";
		colName = "facultyId";
		}
		else{
			whereClause = "from Faculty where firstName=:searchKey";
			colName = "firstName";
		}
		return sessionFactory.getCurrentSession().createQuery(whereClause).setString("searchKey", searchKey).list();
	}

	 public boolean iskeyNumeric(String key){
		try{
		int newkey = Integer.parseInt(key);
		}
		catch (NumberFormatException ne) {
			return false;
		}
		return true;
	}
}
